package com.tuomaxu.utils;

import com.tuomaxu.config.Configuration;
import com.tuomaxu.config.MappedStatement;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XmlMapperBuilder {
    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public  void parse(InputStream inputStream) throws Exception {
        Document document  = new SAXReader().read(inputStream);
        Element rootElement  = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        List<Element> selectList = rootElement.selectNodes("//select");
        createMappedStatement(selectList,namespace,"select");

        //TODO: 解析其他标签
        List<Element> insertList = rootElement.selectNodes("//insert");
        createMappedStatement(insertList,namespace,"insert");

        List<Element> updateList = rootElement.selectNodes("//update");
        createMappedStatement(updateList,namespace,"update");

        List<Element> deleteList = rootElement.selectNodes("//delete");
        createMappedStatement(deleteList,namespace,"delete");


    }

    private void createMappedStatement(List<Element> list,String namespace,String sqlType){
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sqlText = element.getTextTrim();

            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setSql(sqlText);
            mappedStatement.setSqlType(sqlType);

            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key,mappedStatement);
        }
    }
}
